﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GameObjects
{
    [Serializable]
    public class Board
    {
        private IList<Hex> _board;

        public int Width;
        public int Height;

        public Board(){}

        public Board(int width, int height)
        {
            Width = width;
            Height = height;

            _board = new List<Hex>();

            //for (var i = 0; i < Width; i++)
            //    for (var j = 0; j < Height; j++)
            //    _board[i] = new Hex[height];
        }

        public Hex this[int x, int y]
        {
            get
            {
                return _board.Single(o => o.X == x && o.Y == y);
            }
            set
            {
                var hex = _board.SingleOrDefault(o => o.X == x && o.Y == y);
                if (hex == null)
                    _board.Add(value);
                else
                    hex = value;
            }
        }

        public IList<Hex> Hexes
        {
            get { return _board; }
        }

        internal void AddCell(int x, int y, Hex cell)
        {
            cell.X = x;
            cell.Y = y;

            this[x, y] = cell;
        }

        public IEnumerable<Hex> GetAdjacentCells(Hex origin)
        {
            var adjacentCells = new List<Hex>();

            if (origin.Y - 1 >= 0)
                adjacentCells.Add(this[origin.X, origin.Y - 1]);

            if (origin.Y + 1 < Height)
                adjacentCells.Add(this[origin.X, origin.Y + 1]);

            if (origin.X - 1 >= 0)
            {
                if (origin.X % 2 == 0)
                {
                    if (origin.Y - 1 >= 0)
                        adjacentCells.Add(this[origin.X - 1, origin.Y - 1]);

                    adjacentCells.Add(this[origin.X - 1, origin.Y]);

                }
                else
                {
                    adjacentCells.Add(this[origin.X - 1, origin.Y]);

                    if (origin.Y + 1 < Height)
                        adjacentCells.Add(this[origin.X - 1, origin.Y + 1]);
                }
            }
            if (origin.X + 1 < Width)
            {
                if (origin.X % 2 == 0)
                {
                    if (origin.Y - 1 >= 0)
                        adjacentCells.Add(this[origin.X + 1, origin.Y - 1]);

                    adjacentCells.Add(this[origin.X + 1, origin.Y]);

                }
                else
                {
                    adjacentCells.Add(this[origin.X + 1, origin.Y]);

                    if (origin.Y + 1 < Height)
                        adjacentCells.Add(this[origin.X + 1, origin.Y + 1]);
                }
            }

            return adjacentCells;
        }
    }
}
